<?php

namespace app\api\model;

use app\api\controller\sales\SaleAdmin;
use app\common\services\BaseServices;
use think\Model;
use think\Db;
use think\Exception;
use app\common\model\ClaimOrder;
use app\common\logic\ProductLogic;
use app\common\logic\ActionsRecordLogic;
use app\common\logic\ShenZhenPingAnEmployerLogic;
use think\db\Query;


class PcCheck extends Model
{
    private static $instance = null;

	public function __construct($data = [])
    {
        parent::__construct($data);
    }   
    
    /**
     * pc端获得订单详情
     * $num_id
     * 保障中、已失效、待生效
     */
    public function getPcOrderDetail($num_id)
    {
        
        $info = Db::name('order')->alias('o')
            ->join('t_career_type ct', 'o.career_type = ct.id', 'left')
            ->join('t_career_work cw', 'o.career_work = cw.id', 'left')
            ->join('t_product pr', 'o.pro_id = pr.id', 'left')
            ->join('t_product_program p', 'o.program_id = p.id', 'left')
            ->join('t_program pg', 'p.program_id = pg.id', 'left')
            ->where(['o.num_id' => ['eq', $num_id]])
            ->field('o.num_id, o.s_time, o.e_time, o.c_time, o.status, o.policy_money, o.pay_type, o.policy_num, o.pro_id,
                    ct.name AS job_name, cw.name AS work_name, pr.name AS product_name,o.policy_url,o.bill_url,
                    pr.company_id, p.safeguard')
            ->find();
        
        //订单图片     1：保障中   4：已失效    5：待生效         
        $today = time();
        $s_time = strtotime($info['s_time']);
        $e_time = strtotime($info['e_time']);
        if(($today < $e_time) && (($info['status'] == 5) || $info['status'] == 6)){
            $info['type'] = 1;
        }elseif(($today > $e_time) || ($info['status'] == 6)){
            $info['type'] = 4;
        }else{
            $info['type'] = 5;
        }
        
        $info['company_name'] = '中国平安';//config('companys.list')[$info['company_id']];
        $info['new_safeguard'] = \GuzzleHttp\json_decode($info['safeguard'], true);
        $info['Safeguard'] = [$info['new_safeguard'][0]['money'], $info['new_safeguard'][1]['money'], $info['new_safeguard'][2]['money']];
        unset($info['new_safeguard'],$info['safeguard']);
       
        //发票信息
        $info['invoice'] = Db::name('order_invoice')->where(array('num_id' => $num_id))->field('type,taxpayer_name,taxpayer_id')->find();
        
        //判断订单是否可新增、替换人员
        $check_rate = Db::table('t_product_correct_rate')->where(['pro_id' => $info['pro_id'], 'status' => '1'])->column('rate, is_add, is_change, correction_rate_form, correction_rate', 'month');
        $monthDay = BaseServices::getInstance()->getMonth($info['s_time'], $info['e_time']);
        $monthDay['month'] = empty($monthDay['month']) ? 1 : ($monthDay['month'] > 12 ? 12 : $monthDay['month']);
        $info['is_change'] = $check_rate[$monthDay['month']]['is_change'];
        $info['is_add'] = $check_rate[$monthDay['month']]['is_add'];
        
        //在保人员
        $nowwhere = [
            'num_id' => $num_id,
            'status' => 2,
            's_time' => ['elt', datetime(time(), 'Y-m-d') . ' 00:00:00'],
            'e_time' => ['gt', datetime(time(), 'Y-m-d') . ' 00:00:00'],
        ];
        $info['nowData'] = Db::name('employee_info_record')
            ->field('name,paper_num,s_time,e_time,job_name,money')
            ->where($nowwhere)
            ->select();
        
        //待生效
        $futurewhere = [
            'num_id' => $num_id,
            'status' => ['in', [1, 2, 4]],
            's_time' => ['gt', datetime(time(), 'Y-m-d') . ' 23:59:59'],
        ];
        $info['futureData'] = Db::name('employee_info_record')
            ->field('name,paper_num,s_time,e_time,job_name,money')
            ->where($futurewhere)
            ->select();
        
        //过保人员
        $pastwhere = [
            'num_id' => $num_id,
            'is_insured' => 0,
            'e_time' => ['lt', datetime(time(), 'Y-m-d') . ' 23:59:59'],
        ];
        $info['pastData'] = Db::name('employee_info_record')
            ->field('name,paper_num,s_time,e_time,job_name,money')
            ->where($pastwhere)
            ->select();
        
        return array('code'=>200, 'msg'=>'数据提交成功', 'data'=>$info);
    }    
    
    /**
     * pc端保单详情搜索功能
     * name/paper_num/num_id
     * 1：保障中； 4：已失效；5：待生效
     */
    public function searchEmployee($params)
    {
        
        if(isset($params['paper_num'])){
            $where['paper_num'] = array('like','%'.$params['paper_num'].'%');
        }
        
        if(isset($params['name'])){
            $where['name'] = array('like','%'.$params['name'].'%');
        }
        
        $where['num_id'] = $params['num_id'];
        
        if(isset($params['type'])){
            if($params['type'] == 1){
                $where['status'] = 2;
                $where['is_insured'] = 1;
                $where['s_time'] = array('elt', datetime(time(), 'Y-m-d') . ' 00:00:00');
                $where['e_time'] = array('gt', datetime(time(), 'Y-m-d') . ' 00:00:00');
            }else if($params['type'] == 5){
                $where['status'] = ['in', [1, 2, 4]];
                $where['s_time'] = array('gt', datetime(time(), 'Y-m-d') . ' 23:59:59');
            }else{
                $where['is_insured'] = 0;
                $where['e_time'] = array('lt', datetime(time(), 'Y-m-d') . ' 23:59:59');
            }
        }
        
        $employee = Db::name('employee_info_record')
            ->field('name,paper_num,s_time,e_time,job_name,money')
            ->where($where)
            ->select();
        
        return array('code'=>200, 'msg'=>'数据提交成功', 'data'=>$employee);
    }
    
    
    /**
     * pc端保单批改接口
     */
    public function order_check($num_id)
    {
        $info = Db::name('order')->alias('o')
            ->join('t_career_type ct', 'o.career_type = ct.id', 'left')
            ->join('t_career_work cw', 'o.career_work = cw.id', 'left')
            ->join('t_product pr', 'o.pro_id = pr.id', 'left')
            ->join('t_product_program p', 'o.program_id = p.id', 'left')
            ->join('t_program pg', 'p.program_id = pg.id', 'left')
            ->where(['o.num_id' => ['eq', $num_id]])
            ->field('o.num_id, o.s_time, o.e_time, o.c_time, o.status, o.policy_money, o.pay_type, o.policy_num,
                    ct.name AS job_name, 
                    cw.name AS work_name, 
                    pr.company_id, pr.name AS product_name, pr.id as pro_id,
                    p.safeguard, p.year_money')
            ->find();
                    
        $info['company_name'] = '中国平安';//config('companys.list')[$info['company_id']];
        $info['new_safeguard'] = \GuzzleHttp\json_decode($info['safeguard'], true);
        $info['Safeguard'] = [$info['new_safeguard'][0]['money'], $info['new_safeguard'][1]['money'], $info['new_safeguard'][2]['money']];
        unset($info['new_safeguard'],$info['safeguard']);
         
        //判断订单是否可新增、替换人员
        $check_rate = Db::table('t_product_correct_rate')->where(['pro_id' => $info['pro_id'], 'status' => '1'])->column('rate, is_add, is_change, correction_rate_form, correction_rate', 'month');
        $monthDay = BaseServices::getInstance()->getMonth($info['s_time'], $info['e_time']);
        $monthDay['month'] = empty($monthDay['month']) ? 1 : ($monthDay['month'] > 12 ? 12 : $monthDay['month']);
        $info['is_change'] = $check_rate[$monthDay['month']]['is_change'];
        $info['is_add'] = $check_rate[$monthDay['month']]['is_add'];
        
        //在保人员
        $nowwhere = [
            'num_id' => $num_id,
            'status' => 2,
            'is_insured' => 1,
            's_time' => ['elt', datetime(time(), 'Y-m-d') . ' 00:00:00'],
            'e_time' => ['gt', datetime(time(), 'Y-m-d') . ' 00:00:00'],
        ];
        $info['nowData'] = Db::name('employee_info_record')
            ->field('id,name,paper_num,s_time,e_time,job_name,money')
            ->where($nowwhere)
            ->select();
        
        //保单最早生效日期
        $info['min_date'] = ProductLogic::getDisabledChooseStartDate($info['pro_id'], 'correction_date');
        
        //计算投保单剩余月数或者天数得出增加人员的保费
        $check_rate = Db::table('t_product_correct_rate')->where(['pro_id' => $info['pro_id'], 'status' => '1'])->column('rate, is_add, is_change, correction_rate_form, correction_rate', 'month');
        $monthTotal = BaseServices::getInstance()->getMonth($info['s_time'], $info['e_time']);
        $monthTotal['month'] = $monthTotal['month'] - intval((time() - strtotime($info['s_time']))/3600/24/30);
        $monthTotal['month'] = $monthTotal['month'] <= 0 ? 1 : ($monthTotal['month'] >= 12 ? 12 : $monthTotal['month']);
        $check_rate[$monthTotal['month']]['correction_rate'] = $check_rate[$monthTotal['month']]['correction_rate'] <= 0 ? $check_rate[$monthTotal['month']]['rate'] : $check_rate[$monthTotal['month']]['correction_rate'];
        $info['year_money'] = empty($check_rate[$monthTotal['month']]['correction_rate_form']) ? $info['year_money'] * $check_rate[$monthTotal['month']]['correction_rate'] / 100 : $info['year_money'] / 365 * $check_rate[$monthTotal['month']]['correction_rate'] / 100 * $monthTotal['day'];
          
        return array('code'=>200, 'msg'=>'数据提交成功', 'data'=>$info);
    }
    
    /**
     * pc端批改详情数据
     */
    public function checkDetail($params)
    {
         
        $row = Db::table('t_policy_info_change')->alias('oc')
            ->join('t_order o', 'oc.num_id = o.num_id', 'left')
            ->join('t_career_type ct', 'o.career_type = ct.id', 'left')
            ->join('t_career_work cw', 'o.career_work = cw.id', 'left')
            ->join('t_product_program pp', 'o.program_id = pp.id', 'left')
            ->join('t_product p', 'o.pro_id = p.id', 'left')
            ->join('t_order_applicant oa', 'o.num_id = oa.num_id', 'left')
            ->join('t_order_assured os', 'o.num_id = os.num_id', 'left')
            ->field('oc.num_id,oc.id as check_id,oc.s_time as check_s_time,oc.insure_file,oc.electronic_file,oc.change_bill_url,oc.check_num,oc.check_inc,oc.check_dec,oc.money,oc.check_status,
                    o.policy_money,o.policy_num,o.status,o.c_time,o.s_time,o.e_time,o.applicant_name,
                    ct.name AS job_name, cw.name AS work_name,
                    p.company_id,p.name as pro_name,p.company_id,
                    pp.safeguard,
                    os.name as assured_name
                    ')
            ->where(['oc.id' => $params['change_id']])
            ->find();
            
        if ($row['company_id'] == 12)
        {
            if (!$row['electronic_file'] && $row['check_num']) { //电子批单
                $row['electronic_file'] = url('/admin/ordercheck/check/getPolicy', ['id' => $params['change_id'], 'type' => 0, 'authCheck' => 0]);
            }
            if (empty($row['change_bill_url'])) { //电子发票
                $row['change_bill_url'] = url('/admin/ordercheck/check/getPolicy', ['id' => $params['change_id'], 'type' => 1, 'authCheck' => 0]);
            }
        }
        
        $row['company_name'] = '中国平安';//config('companys.list')[$row['company_id']];
        $row['new_safeguard'] = \GuzzleHttp\json_decode($row['safeguard'], true);
        $row['Safeguard'] = [$row['new_safeguard'][0]['money'], $row['new_safeguard'][1]['money'], $row['new_safeguard'][2]['money']];
        unset($row['new_safeguard'],$row['safeguard'],$row['company_id']);
        
        //增加人员
        $addwhere = [
            'num_id' => $params['num_id'],
            'type' => 1,
            'change_info_id' => $params['change_id'],
        ];
        $row['addData'] = Db::name('employee_info_record')
            ->field('name,paper_num,s_time,e_time,job_name,money')
            ->where($addwhere)
            ->select();
        
        //批减人员
        $change_id = $params['change_id'];
        $numId = $params['num_id'];
        $where = [
           'id' => ['in', function ($query) use ($numId,$change_id) {
                $query->table('t_employee_info_record')
                ->where('num_id', $numId)
                ->where('change_info_id', $change_id)
                ->where('change_id', 'neq', '0')
                ->field('change_id');
                }],
            'num_id' => ['eq', $numId],
        ];
        $row['desData'] = Db::name('employee_info_record')
           ->where($where)
           ->field('name,paper_num,s_time,e_time,job_name,money')
           ->order('id desc')
           ->select();
           
        return array('code'=>200, 'msg'=>'数据提交成功', 'data'=>$row);
    }
    
    /**
     * 保单人员批改提交
     */
    public function checkOrderSubmit($param)
    {
        $member = json_decode($param['members'], true);
        
        $ids = array_column($member, 'id');
        $is_replace = false;//是否替换 就无需付款
        $inc_member = count($member) - count($ids);
        
        if ($param['money'] == 0) {
            $is_replace = true;
        }
        
        //获得订单数据
        $order = Db::name('order')->where(['num_id' => $param['num_id']])->find();
        
        $producutOther = Db::name('product_other')->where('pro_id', $order['pro_id'])
                ->field('min_age,max_age,company_bank_name,company_bank_no,company_username')
                ->find();
        
        $job_name = Db::name('career_work')->where(['id' => $order['career_work']])->value('name');
        $identity = new \fast\Identity();
        
        Db::startTrans();
        try {
            $time = datetime(time());
            $s_time = !empty($param['s_time']) ? $param['s_time'] : datetime(strtotime('+1 day'), 'Y-m-d');
            $check_inc = count($ids) + $inc_member;
            $check_dec = count($ids);
            
            $check_status = $is_replace ? 0 : 3;
            $data = [
                'num_id' => $param['num_id'],
                's_time' => $s_time,
                'e_time' => $order['e_time'],
                'money' => !empty($param['money']) ? $param['money'] : 0,
                'pay_type' => $order['pay_type'],
                'check_inc' => $check_inc,
                'check_dec' => $check_dec,
                'check_status' => $check_status,
                'uid' => $param['uid'],
            ];
            
            $data['c_time'] = $time;
//             $data['change_file'] = $param['change_file'];
            $row = Db::table('t_policy_info_change')->insert($data);
            $id = Db::table('t_policy_info_change')->getLastInsID();
            $msg = '数据提交成功，请等待审核';
            $action_name = '批单提交';
            
            if ($row) {
                $add_num = 1;
                $del_num = 1;
                $addData = [];
                $delData = [];
                $changeData = [];
                
                foreach ($member as &$v) {
                    if (!$identity->isID($v['paper_num'])) {
                        return array('code'=>202, 'msg'=> '证件号为：' . $v['paper_num'] . '的人员证件有误，请更改');
                    }
                    $arr['change_info_id'] = $id;
                    $arr['employee_code'] = '';
                    $arr['num_id'] = $param['num_id'];
                    $arr['uid'] = $param['uid'];
                    $arr['c_time'] = $time;
                    $arr['s_time'] = $s_time;
                    $arr['e_time'] = $order['e_time'];
                    $arr['name'] = $v['name'];
                    $row = Db::table('t_employee_info_record')
                        ->where(['paper_num' => $v['paper_num'], 'num_id' => $param['num_id'], 'uid' => $param['uid'], 'is_insured' => '1'])
                        ->count();
                    if ($row) {
                        return array('code'=>202, 'msg'=> '证件号为：' . $v['paper_num'] . '的人员已存在');
                    }
                    
                    //该数据是否重复添加
                    $repeat = Db::table('t_employee_info_record')
                        ->where(['paper_num' => $v['paper_num'], 'num_id' => $param['num_id'], 'uid' => $param['uid'], 'is_insured' => '0', 'status'=>4])
                        ->count();
                    if ($repeat) {
                        return array('code'=>202, 'msg'=> '证件号为：' . $v['paper_num'] . '的人员已提交，不能重复提交');
                    }
                    
                    $res = Db::table('t_employee_info_record')
                        ->where(['paper_num' => $v['paper_num'], 'e_time' => ['egt', $s_time], 'status' => '2', 'is_insured' => '1'])
                        ->column('num_id');
                    if (!empty($res)) {
                        $row = Db::table('t_order')->where(['num_id' => ['in', $res], 'pro_id' => $order['pro_id'], 'status' => '6'])->count();
                        if ($row) {
                            return array('code'=>202, 'msg'=> '证件号为：' . $v['paper_num'] . '的人员已有在该产品保障中');
                        }
                    }
                    $arr['sex'] = $identity->getSex($v['paper_num']);
                    $arr['age'] = $identity->getAge($v['paper_num']);
                    if ($arr['age'] < $producutOther['min_age'] || $arr['age'] > $producutOther['max_age']) {
                        return array('code'=>202, 'msg'=> '证件号为：' . $v['paper_num'] . '的人员年龄不在' . $producutOther['min_age'] . '-' . $producutOther['max_age'] . '之间，请修改');
                    }
                    $arr['paper_type'] = 1;
                    $arr['paper_num'] = $v['paper_num'];
                    $arr['job_name'] = $job_name;
                    $arr['status'] = $is_replace ? 1 : 4;
                    $arr['money'] = !empty($param['year_money']) ? $param['year_money'] : 0;
                    $arr['type'] = 1;
                    $arr['change_id'] = !empty($v['id']) ? $v['id'] : 0;
                    $dat[] = $arr;
                    $arr['num'] = $add_num;
                    $arr['flag'] = '新增';
                    $arr['operate_status'] = 'A';
                    $addData[] = $arr;
                    unset($arr['num'], $arr['flag']);
                    if (!empty($v['id'])) {
                        Db::name('employee_info_record')->where(['id' => $v['id']])->update(['e_time' => datetime(strtotime($s_time) - 3600*24, 'Y-m-d').' 23:59:59', 'is_insured' => 0]);
                        
                        $row = Db::table('t_employee_info_record')
                            ->where(['id' => $v['id']])->field('name,paper_num,sex,job_name')->find();
                        $row['num'] = $del_num;
                        $row['s_time'] = $s_time;
                        $row['flag'] = '减少';
                        $arr['operate_status'] = 'C';
                        $arr['old_name'] = $row['name'];
                        $arr['old_paper_num'] = $row['paper_num'];
                        $arr['operate_status'] = 'C';
                        $delData[] = $row;
                        $del_num++;
                    }
                    $changeData[] = $arr;
                    unset($arr['old_name'], $arr['old_paper_num'], $arr['operate_status']);
                    $add_num++;
                }
                
                $jumpurl = url('/admin/ordercheck/check/index', ['ref' => 'addtabs']);
                
                //线下批改只需要审核时请求批改接口
                $work = Db::name('career_work')->where(['id' => $order['career_work']])->field('name,type')->find();
                $params = [
                    'pay_type' => $order['pay_type'],
                    'money' => $param['money'],
                    's_time' => $s_time . ' 00:00:00',
                    'employerList' => $changeData,
                    'policy_num' => $order['policy_num'],
                    'num_id' => $param['num_id'],
                    'work_type' => $work['type'],
                    'work_name' => $work['name'],
                    'applicant_name' => $order['applicant_name'],
                    'protect_num' => $order['protect_num'],
                    'change_id' => $id,
                    'add_count' => count($addData)
                ];
                //批改
                $change_info = Db::table('t_policy_info_change')->where(['id' => $id])->field('change_num,ext_info')->find();//批单申请号
                if (!$change_info['change_num']) {
                     $res = ShenZhenPingAnEmployerLogic::getInstance()->correct($params);

                     if (!$res['code']) {
                         return array('code'=>202, 'msg'=> $res['msg']);
                     }
                     $res = $res['data'];
                     if (floatval($res['amount']) != floatval($param['money'])) {
                         Db::table('t_policy_info_change')->where(['id' => $id])->update(['money' => $res['amount']]);
                         Db::table('t_employee_info_record')->where(['change_info_id' => $id, 'change_id' => 0])->update(['money' => bcdiv($res['amount'], count($addData), 2)]);
                     }

                    Db::table('t_employee_info_record')->insertAll($dat);
                    ActionsRecordLogic::getInstance()->add($param['uid'], $id, 2, $action_name);
                    Db::commit();
                } else {
                    $res = json_decode($change_info['ext_info'], true);
                }
                
                Db::startTrans();
                 if (in_array($order['pay_type'], [0,4])) {//平安雇主线上批改
                     if (!$is_replace) {
                         $res['change_id'] = $id;
                         $res = ShenZhenPingAnEmployerLogic::getInstance()->correctPay($res);
                        
                         if (!$res['code']) {
                             return array('code'=>202, 'msg'=> $res['msg']);
                         }
                     }
                 } else {
                     Db::table('t_policy_info_change')->where(['id' => $id])->update(['ext_info' => json_encode($params)]);
                 }
                if (!$is_replace) { //增加人员需要跳转支付
                    
                    if($order['pay_type'] != 1){
                        
                        $return['pay_type'] = 0;
                    }else{
                        $return['pay_type'] = 1;
                    }

                    $saleAdmin = new SaleAdmin();
                    $saleAdmin->retailStore([
                        'num_id' => $param['num_id'],
                        'change_id' => $id,
                        'uid' => Db::name('user')->where(['id' => $param['uid']])->value('pid'),
                        'pro_id' => $order['pro_id'],
                        'policy_money' => $res['amount']
                    ]);

                    $return['change_id'] = $id;
                    $return['company_bank_name'] = $producutOther['company_bank_name'];
                    $return['company_bank_no'] = $producutOther['company_bank_no'];
                    $return['company_username'] = $producutOther['company_username'];
                    
                    $return['money'] = $param['money'];
                    $return['is_replace'] = 1;
                } else {
                    //只有替换不需要审核
                    $wh = ['num_id' => $param['num_id'], 'change_info_id' => $id];
                    Db::table('t_employee_info_record')
                        ->where($wh)
                        ->update(['u_time' => datetime(time()), 'status' => 2, 'is_insured' => 1]);
                    Db::table('t_policy_info_change')->where(['id' => $id])->update(['check_status' => 1, 'u_time' => datetime(time())]);
                    $msg = '数据提交成功';
                    $return['is_replace'] = 0;
                }
                Db::commit();
                
                return array('code'=>200, 'msg'=> '添加成功', 'data'=>$return);
            }else{
                return array('code'=>202, 'msg'=> '信息未修改，请勿提交');
            }
            
        } catch (\think\exception\PDOException $e) {
            // 回滚事务
            Db::rollback();
            return array('code'=>202, 'msg'=> $e->getMessage() . $e->getLine() . $e->getFile());
        }
    }
    
    /**
     * 数据留存
     */
    public function getRetention($params)
    {
        $result = array();
        $data = Db::name('order_retention')->where(array('retention_code'=>$params['retention_code']))->select();
        foreach($data as $key => $val){
            $result[$val['retention_step']] = $val;
        }
        return $result;
    }
}

